package com.example.zuul.filter;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * 自定义异常处理
 * 出现异常时，此过滤器被执行
 **/
@Component
@Slf4j
public class ErrorFilter extends ZuulFilter {

    @Override
    public String filterType() {
        // 错误过滤器
        return FilterConstants.ERROR_TYPE;
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletResponse response = currentContext.getResponse();
        ZuulException exception = (ZuulException) currentContext.get("throwable");

        HashMap<String, String> massage = new HashMap<>();
        massage.put("massage", exception.getMessage());
        massage.put("code", "500");

        JSON res = JSONUtil.parse(massage);
        try {
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(res.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
